package org.xp.judgeplatform.security;

import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.xp.judgeplatform.pojo.entity.User;

import java.util.Collection;
import java.util.Collections;

/**
 * 自定义UserDetails实现
 * 包装User实体，提供完整的用户信息
 */
@Getter
public class UserPrincipal implements UserDetails {

    private final User user;
    private final Collection<? extends GrantedAuthority> authorities;

    public UserPrincipal(User user) {
        this.user = user;
        this.authorities = Collections.singletonList(
            new SimpleGrantedAuthority(user.getRole().toUpperCase())
        );
    }

    // 获取用户ID（新增方法，方便Controller使用）
    public Integer getId() {
        return user.getId();
    }

    // 获取完整的User实体
    public User getUser() {
        return user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return "NORMAL".equals(user.getStatus());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return "NORMAL".equals(user.getStatus());
    }
}

